import 'dart:convert';

import 'package:http/http.dart' as http;

const apiKey = '377dff66ad5c79e6609c63d89528500e';
const exchangeURL = 'http://op.juhe.cn/onebox/exchange/currency';

class NetworkHelper {
  /// 获取汇率数据
  /// 返回格式: 汇率字符串 (如 "0.15"), 失败时返回空字符串
  Future<String> getExchangeRate(String selectedCurrency) async {
    try {
      // 1. 提取货币代码前3位 (如 "CNY")
      final currencyCode = selectedCurrency.substring(0, 3);

      // 2. 构建请求URL
      final uri = Uri.parse(
        '$exchangeURL?key=$apiKey&from=$currencyCode&to=USD&version=2',
      );

      // 3. 发起网络请求
      final response = await http.get(uri);

      // 4. 处理响应
      if (response.statusCode == 200) {
        final jsonData = jsonDecode(response.body);
        return jsonData['result'][0]['exchange'].toString(); // 确保返回字符串
      } else {
        print('[NetworkHelper] 请求失败，状态码: ${response.statusCode}');
        return '';
      }
    } catch (e) {
      print('[NetworkHelper] 发生异常: $e');
      return '';
    }
  }
}
